package io.kiki.sba.registry.server.clientInterface.resource;

import com.fasterxml.jackson.core.type.TypeReference;
import io.kiki.sba.registry.common.model.CollectionSdks;
import io.kiki.sba.registry.common.model.GenericResponse;
import io.kiki.sba.registry.common.model.Response;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerAddress;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerAddress.AddressVersion;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerResult;
import io.kiki.sba.registry.server.clientInterface.client.manager.CheckClientManagerService;
import io.kiki.sba.registry.server.shared.client.manager.ClientManagerService;
import io.kiki.sba.registry.store.api.DBResponse;
import io.kiki.sba.registry.store.api.OperationStatus;
import io.kiki.sba.registry.util.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Set;


@Path("api/clientManager/persistence")
@Produces(MediaType.APPLICATION_JSON)
public class PersistenceClientManagerResource {
    public static final TypeReference<Set<AddressVersion>> FORMAT = new TypeReference<Set<AddressVersion>>() {
    };
    private static final Logger logger = LoggerFactory.getLogger(ClientManagerResource.class);
    @Autowired
    private ClientManagerService clientManagerService;

    @Autowired
    private CheckClientManagerService checkClientManagerService;

    /**
     * Client off
     */
    @POST
    @Path("/clientOff")
    public GenericResponse<Long> clientOff(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return new GenericResponse().fillFailed("clientOff ips is empty.");
        }
        Set<String> ipSet = CollectionSdks.toIpSet(ips);

        ClientManagerResult ret = clientManagerService.clientOff(ipSet);
        logger.info("client off result:{}, ips:{}", ret, ips);

        GenericResponse<Long> response = new GenericResponse();
        response.setSuccess(ret.isSuccess());
        response.setData(ret.getVersion());
        return response;
    }

    @POST
    @Path("/clientOffWithSub")
    public GenericResponse<Long> clientOffWithSub(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return new GenericResponse().fillFailed("clientOffWithSub ips is empty.");
        }

        Set<AddressVersion> read = JsonUtils.read(ips, FORMAT);
        if (!validate(read)) {
            logger.error("client off new error, ips:{}", read);
            return new GenericResponse().fillFailed("ips is invalidate.");
        }

        ClientManagerResult ret = clientManagerService.clientOffWithSub(read);

        logger.info("clientOffWithSub result:{}, ips:{}", ret, ips);

        GenericResponse<Long> response = new GenericResponse();
        response.setSuccess(ret.isSuccess());
        response.setData(ret.getVersion());
        return response;
    }

    private boolean validate(Set<AddressVersion> list) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        for (AddressVersion address : list) {
            if (!address.isPub() && !address.isSub()) {
                return false;
            }
        }
        return true;
    }


    @POST
    @Path("/clientOpen")
    public GenericResponse<Long> clientOpen(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return new GenericResponse().fillFailed("clientOpen ips is empty.");
        }
        Set<String> ipSet = CollectionSdks.toIpSet(ips);

        ClientManagerResult ret = clientManagerService.clientOpen(ipSet);

        logger.info("client open result:{}, ips:{}", ret, ips);

        GenericResponse<Long> response = new GenericResponse();
        response.setSuccess(ret.isSuccess());
        response.setData(ret.getVersion());
        return response;
    }


    @POST
    @Path("/reduce")
    public GenericResponse<Long> reduce(@FormParam("ips") String ips) {
        if (StringUtils.isBlank(ips)) {
            return new GenericResponse().fillFailed("reduce ips is empty.");
        }
        Set<String> ipSet = CollectionSdks.toIpSet(ips);

        ClientManagerResult ret = clientManagerService.reduce(ipSet);

        logger.info("reduce result:{}, ips:{}", ret, ips);

        GenericResponse<Long> response = new GenericResponse();
        response.setSuccess(ret.isSuccess());
        response.setData(ret.getVersion());
        return response;
    }

    @GET
    @Path("/checkVersion")
    public Response checkVersion(@QueryParam("version") String version) {
        try {
            long expectedVersion = Long.parseLong(version);
            boolean check = checkClientManagerService.check(expectedVersion);
            logger.info("check version: {} ret: {}", version, check);
            Response response = Response.buildSuccessResponse();
            response.setSuccess(check);
            return response;
        } catch (Throwable t) {
            logger.error("check version: {} fail.", version, t);
            Response response = Response.buildFailedResponse("check version fail.");
            return response;
        }
    }

    @GET
    @Path("/query")
    public GenericResponse<ClientManagerAddress> query() {
        DBResponse<ClientManagerAddress> ret = clientManagerService.queryClientOffAddress();
        logger.info("client off result:{}", ret.getOperationStatus(), ret.getEntity());

        if (ret.getOperationStatus() != OperationStatus.success) {
            return new GenericResponse<ClientManagerAddress>().fillFailed("data not found");
        }
        return new GenericResponse<ClientManagerAddress>().fillSucceed(ret.getEntity());
    }


    public PersistenceClientManagerResource setClientManagerService(ClientManagerService clientManagerService) {
        this.clientManagerService = clientManagerService;
        return this;
    }
}
